#! /bin/sh
#
# Copyright (c) 2014-2016,2023 Red Hat.
# Copyright (c) 2005 Silicon Graphics, Inc.  All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#
# Start or Stop the Performance Co-Pilot (PCP) pmproxy process.
#
# This script expects to be run as pcp:pcp, either from systemd via the
# pmproxy.service or from init (or similar) via the rc_wrapper script
# installed in $PCP_RC_DIR/pmproxy
#

. $PCP_DIR/etc/pcp.env
. $PCP_SHARE_DIR/lib/rc-proc.sh

# for chasing arguments we're passed from init/systemd/...
#
#debug# echo "$*: `date`" >>$PCP_LOG_DIR/rc_pmproxy.log
#debug# env >>$PCP_LOG_DIR/rc_pmproxy.log

PMPROXY=$PCP_BINADM_DIR/pmproxy
PMPROXYENVS=$PCP_SYSCONFIG_DIR/pmproxy
pmprog=$PCP_SERVICES_DIR/pmproxy
prog=$PCP_SYSCONF_DIR/pmproxy/`basename $0`

tmp=`mktemp -d "$PCP_TMPFILE_DIR/pmproxy_rc.XXXXXXXXX"` || exit 1
status=1
trap "rm -rf $tmp; exit \$status" 0 1 2 3 15

# optional begin logging to $PCP_LOG_DIR/NOTICES
#
if $PCP_LOG_RC_SCRIPTS
then
    logmsg="begin pid:$$ $prog args:$*"
    if which pstree >/dev/null 2>&1
    then
	logmsg="$logmsg [`_pstree_oneline $$`]"
    fi
    $PCP_BINADM_DIR/pmpost "$logmsg"
fi

if [ $pmprog = $prog ]
then
    VERBOSE_CTL=on
else
    VERBOSE_CTL=off
fi

case "$PCP_PLATFORM"
in
    mingw)
	# nothing we can usefully do here, skip the test
	#
	;;

    *)
	# standard Unix/Linux style test
	#
	ID=id
	test -f /usr/xpg4/bin/id && ID=/usr/xpg4/bin/id

	IAM=`$ID -u 2>/dev/null`
	if [ -z "$IAM" ]
	then
	    # do it the hardway
	    #
	    IAM=`$ID | sed -e 's/.*uid=//' -e 's/(.*//'`
	fi
	;;
esac

_shutdown()
{
    # Is pmproxy running?
    #
    _get_pids_by_name pmproxy >$tmp/tmp
    if [ ! -s $tmp/tmp ]
    then
	[ "$1" = verbose ] && echo "$pmprog: pmproxy not running"
	rm -f $PCP_RUN_DIR/pmproxy.pid $PCP_RUN_DIR/pmproxy.socket
	return 0
    fi

    # Send pmproxy a SIGTERM, which is noted as a pending shutdown.
    # When finished the currently active request, pmproxy will close any
    # connections and then exit.
    # Wait for pmproxy to terminate.
    #
    pmsignal -p -s TERM pmproxy > /dev/null 2>&1

    [ "$1" = quietly ] || \
    $ECHO $PCP_ECHO_N "Waiting for pmproxy to terminate ...""$PCP_ECHO_C"
    gone=0
    for i in 1 2 3 4 5 6
    do
	sleep 3
	_get_pids_by_name pmproxy >$tmp/tmp
	if [ ! -s $tmp/tmp ]
	then
	    gone=1
	    break
	fi

	# If pmproxy doesn't go in 15 seconds, SIGKILL and sleep 1 more time
	# to allow any clients reading from pmproxy sockets to fail so that
	# socket doesn't end up in TIME_WAIT or somesuch.
	#
	if [ $i = 5 ]
	then
	    $ECHO
	    echo "Process ..."
	    $PCP_PS_PROG $PCP_PS_ALL_FLAGS >$tmp/ps
	    sed 1q $tmp/ps
	    for pid in `cat $tmp/tmp`
	    do
		$PCP_AWK_PROG <$tmp/ps "\$2 == $pid { print }"
	    done
	    echo "$prog: Warning: Forcing pmproxy to terminate!"
	    pmsignal -a -s KILL pmproxy > /dev/null 2>&1
	else
	    $ECHO $PCP_ECHO_N ".""$PCP_ECHO_C"
	fi
    done
    if [ $gone != 1 ]	# It just WON'T DIE, give up.
    then
	echo "Process ..."
	cat $tmp/tmp
	echo "$prog: Warning: pmproxy won't die!"
	exit
    fi
    if [ "$1" = quietly ]
    then
	true && $RC_STATUS
    else
	true && $RC_STATUS -v
    fi
    rm -f $PCP_RUN_DIR/pmproxy.pid
    $PCP_BINADM_DIR/pmpost "stop pmproxy from $pmprog"
}

_usage()
{
    echo "Usage: $pmprog [-v] {start|faststart|restart|condrestart|stop|status|reload|force-reload}"
}

while getopts v c
do
    case $c
    in
	v)  # force verbose
	    VERBOSE_CTL=on
	    ;;
	
	*)
	    _usage
	    exit 1
	    ;;
    esac
done
shift `expr $OPTIND - 1`

if [ $VERBOSE_CTL = on ]
then				# For a verbose startup and shutdown
    ECHO=$PCP_ECHO_PROG
else				# For a quiet startup and shutdown
    ECHO=:
fi

# First reset status of this service
$RC_RESET
 
# Return values acc. to LSB for all commands but status:
# 0 - success
# 1 - misc error
# 2 - invalid or excess args
# 3 - unimplemented feature (e.g. reload)
# 4 - insufficient privilege
# 5 - program not installed
# 6 - program not configured
#
# Note that starting an already running service, stopping
# or restarting a not-running service as well as the restart
# with force-reload (in case signalling is not supported) are
# considered a success.
case "$1" in

  start|start-systemd|faststart|restart|condrestart|reload|force-reload)
	if [ "$1" = "condrestart" ] && ! is_chkconfig_on pmproxy
	then
	    status=0
	    exit
	fi

	_shutdown quietly

	# pmproxy messages should go to stderr, not the GUI notifiers
	#
	unset PCP_STDERR

	if [ -x $PMPROXY ]
	then
	    if [ ! -f "$PCP_PMPROXYOPTIONS_PATH" ]
	    then
		echo "$prog:"'
Error: pmproxy options file $PCP_PMPROXYOPTIONS_PATH ("'"$PCP_PMPROXYOPTIONS_PATH"'") is missing, cannot start pmproxy.'
		exit
	    fi
	    if [ ! -d "$PCP_RUN_DIR" ]
	    then
		echo "$prog:"'
Error: pmproxy runtime directory $PCP_RUN_DIR ("'"$PCP_RUN_DIR"'") is missing, cannot start pmproxy.'
		exit
	    fi
	    if [ ! -d "$PCP_LOG_DIR/pmproxy" ]
	    then
		echo "$prog:"'
Error: pmproxy log directory $PCP_LOG_DIR/pmproxy ("'"$PCP_LOG_DIR/pmproxy"'") is missing, cannot start pmproxy.'
		exit
	    fi
	    cd "$PCP_LOG_DIR/pmproxy"

	    [ "$1" = "start-systemd" ] ||\
	    $ECHO $PCP_ECHO_N "Starting pmproxy ..." "$PCP_ECHO_C"

	    # only consider variables which start with PMPROXY
	    `sed -n 's/^PMPROXY/export PMPROXY/p' < $PMPROXYENVS 2>/dev/null`

	    # only consider lines which start with a hyphen
	    # get rid of the -f option
	    # ensure multiple lines concat onto 1 line
	    OPTS=`sed < "$PCP_PMPROXYOPTIONS_PATH" 2>/dev/null \
			    -e '/^[^-]/d' \
			    -e 's/^/ /' \
			    -e 's/$/ /' \
			    -e 's/ -f / /g' \
			    -e 's/^ //' \
			    -e 's/ $//' \
		    | tr '\012' ' ' `

	    $PCP_BINADM_DIR/pmpost "start pmproxy from $pmprog"

	    if [ "$1" = "start-systemd" ]
	    then
		# Called from systemd with need to preserve the pid and
		# systemd has already done the necessary daemonizing
		#
		rm -rf $tmp
		exec $PMPROXY -F $OPTS
		# NOTREACHED
		#
	    fi

	    # otherwise, use the historical approach
	    #
	    $PMPROXY $OPTS
	    $RC_STATUS -v
	fi
	status=0
        ;;

  stop)
	_shutdown
	status=0
        ;;

  stop-systemd)
	_shutdown quietly
	status=0
        ;;

  status)
	# NOTE: $RC_CHECKPROC returns LSB compliant status values.
	$ECHO $PCP_ECHO_N "Checking for pmproxy:" "$PCP_ECHO_C"
        if [ -r /etc/rc.status ]
        then
            # SuSE
            $RC_CHECKPROC $PMPROXY
            $RC_STATUS -v
            status=$?
        else
            # not SuSE
            $RC_CHECKPROC $PMPROXY
            status=$?
            if [ $status -eq 0 ]
            then
                $ECHO running
            else
                $ECHO stopped
            fi
        fi
	;;

  *)
	_usage
        ;;
esac

# optional end logging to $PCP_LOG_DIR/NOTICES
#
if $PCP_LOG_RC_SCRIPTS
then
    $PCP_BINADM_DIR/pmpost "end pid:$$ $prog status=$status"
fi

exit
